package terra.twl.window;

import java.io.IOException;

import terra.Loader;
import terra.managers.DefManager;
import terra.model.Experience;
import terra.model.ItemClientDef;
import terra.model.Player;
import terra.model.Slot;
import terra.network.packet.client.RequestDropItem;
import terra.slick.GameState;
import terra.twl.RootPane;
import terra.twl.widget.ItemSlot;
import de.matthiasmann.twl.Color;
import de.matthiasmann.twl.ResizableFrame;
import de.matthiasmann.twl.TextArea;
import de.matthiasmann.twl.ThemeInfo;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.Image;
import de.matthiasmann.twl.renderer.Texture.Rotation;
import de.matthiasmann.twl.textarea.HTMLTextAreaModel;

/**
 *
 * @author Matthias Mann
 */
public class CharacterPanel extends Widget implements IDropable{
    
    private final ItemSlot[] slot;
    private int slotSpacing;

    private ItemSlot dragSlot;
    private ItemSlot dropSlot;
    TextArea textarea;
    HTMLTextAreaModel model;
    String html = 					
	"<html>" +
		"<body>" +
			"<table style=\"width: 100%;\">" +
				"<tr>" +
					"<td>CON:</td>" +
					"<td>$con</td>" +
					"<td>Atk:</td>" +
					"<td>$atk</td>" +
				"</tr>"+
				"<tr>" +
					"<td>STR:</td>" +
					"<td>$str</td>" +
					"<td>Def:</td>" +
					"<td>$def</td>" +
				"</tr>" +
				"<tr>" +
					"<td>DEX:</td>" +
					"<td>$dex</td>" +
					"<td>Crit:</td>" +
					"<td>$Cchance</td>" +
				"</tr>" +
			"</table>" +
			"<div style=\"float: left; width: 45%;\">" +
				"Hp:" +
				"<br/>" +
				"Breath:" +
				"<br/>" +
				"Exp:" +
			"</div>" +
			"<div style=\"float: right; width: 45%; text-align: right;\">" +
				"$curHp / $maxHp" +
				"<br/>" +
				"$curBrth / $maxBrth" +
				"<br/>" +
				"$exp / $toLvl" +
			"</div>" +
		"</body>" +
	"</html>";

    public void setHtml(String htm){
    	model.setHtml(htm);	
    }
    
    public void updateHtml(){
    	Player p = GameState.getInstance().player;
    	if (p == null)
    		return;
    	String s = new String(html);
    	s = s.replace("$con", p.getCon()+"");
    	s = s.replace("$str", p.getStr()+"");
    	s = s.replace("$dex", p.getDex()+"");
    	
    	s = s.replace("$maxHp", p.getMaxHp()+"");
    	s = s.replace("$curHp", p.getCurrentHp()+"");
    	s = s.replace("$maxBrth", p.getMaxBreath()+"");
    	s = s.replace("$curBrth", p.getCurrentBreath()+""); 	
    	s = s.replace("$exp", p.getExp()+"");
    	s = s.replace("$toLvl", (Experience.LEVEL[p.getLevel()+1]-Experience.LEVEL[p.getLevel()])+""); 
    	s = s.replace("$atk", p.getAtk()+"");
    	s = s.replace("$def", p.getDef()+"");
    	s = s.replace("$Cchance", p.getCritChance()+"%");
    	setHtml(s);
    	if (getParent() != null)
    		((ResizableFrame) getParent()).setTitle("Character: "+ p.getName() + " "+ p.getLevel()+ " level");
    }
    
    public CharacterPanel() {
    	
    	model = new HTMLTextAreaModel();
    	textarea = new TextArea(model);
    	textarea.setSize(150, 130);
    	add(textarea);
        slot = new ItemSlot[Slot.SLOT_COUNT];

        for(int i=0 ; i<slot.length ; i++) {
            slot[i] = new ItemSlot();
            slot[i].setListener(this);

            add(slot[i]);
        }
    }
    
    public void update(){
    	for(int i = 0 ; i < slot.length;i++){
    		slot[i].reset();
    	}
    	for(int i = 0 ; i < slot.length;i++){
    		ItemClientDef def = GameState.getInstance().inventory.slotItems[i];
    		if (def == null || def.getId() < 0)
    			continue;
    		slot[i].setDef(def);
    	}
    
//    	for(ItemClientDef def : GameState.getInstance().inventory.slotItems){
//    		ItemSlot s = slot[i];
//    		if (slot == null)
//    			getFirstEmpty().setDef(def);
//    		else
//    			slot.setDef(def);
//    	}
    }
     
    @Override
    public int getPreferredInnerWidth() {
        return 300;
    }

    @Override
    public int getPreferredInnerHeight() {
        return 140;
    }

    @Override
    protected void layout() {
        int slotWidth  = slot[0].getPreferredWidth();
        int slotHeight = slot[0].getPreferredHeight();
        
        for(int i =0; i < slot.length;i++){
        	slot[i].adjustSize();
        	slot[i].setPosition(getInnerX()+slotSpacing*(i%3+1)+i%3*slotWidth,getInnerY()+ slotSpacing*(i/3+1)+i/3*slotHeight);
            try {
				slot[i].defaultIcon = (Image) getGUI().getRenderer().loadTexture(
						Loader.class.getResource("graphics/item/"+Slot.getImageBySlotId(i)+".png"), "RGBA", "linear").
						getImage(0, 0, 32, 32, Color.WHITE, false, Rotation.NONE);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        textarea.adjustSize();
    	textarea.setPosition(getInnerX()+150, getInnerY());
    }

    @Override
    protected void applyTheme(ThemeInfo themeInfo) {
        super.applyTheme(themeInfo);
        slotSpacing = themeInfo.getParameter("slotSpacing", 5);
    }
    
    public void dragStarted(ItemSlot slot, int x,int y) {
        if(slot.def != null) {
            dragSlot = slot;
            dragging(slot, x,y);
        }
    }
    
    public void dragging(ItemSlot slot, int x,int y) {
        if(dragSlot != null) {
            Widget w = getWidgetAt(x,y);
            if(w instanceof ItemSlot) {
                setDropSlot((ItemSlot)w);
            } else {
                setDropSlot(null);
            }
        }
    }
    
    public void dragStopped(ItemSlot slot,int x,int y,Object param,Object param2) {
        if(dragSlot != null) {
            dragging(slot, x,y);
            if(dropSlot != null && dropSlot.canDrop() && dropSlot != dragSlot) {
                dropSlot.setDef(dragSlot.def);
                dragSlot.reset();
            } else if (dropSlot == null){
	        	Widget w = GameState.getInstance().getRootPane().getWidgetAt(x,y);
	        	System.out.println("dragStopped on widget: "+ w);

	        	if (w == null || w instanceof RootPane) {
	    			if (slot.def.getCount() == 1 || !DefManager.allItems.get(slot.def.getId()).isStackable) {
	    				RequestDropItem request = new RequestDropItem(GameState.getInstance().player.getObjectId(),slot.def.getOId(), slot.def.getId(), x,y,1);
	    				Loader.handler.send(request);
	    			}
	    			else
	    				GameState.getInstance().countchooser.init(slot,x,y,null,this);
	        	} else {
	        		if (w instanceof IDropable)
	        			((IDropable) w).dragStopped(slot, x,y,null,null);
	        	}
            }
        }
        setDropSlot(null);
        dragSlot = null;
    	}

    private void setDropSlot(ItemSlot slot) {
        if(slot != dropSlot) {
            if(dropSlot != null) {
                dropSlot.setDropState(false, false);
            }
            dropSlot = slot;
            if(dropSlot != null) {
                dropSlot.setDropState(true, dropSlot == dragSlot || dropSlot.canDrop());
            }
        }
    }
}
